import random
import datetime
from flask import abort, Blueprint, g, render_template, session, current_app

from .database import db
from .auth import login_required
from .crud import Users, Courses, Attendances
from . import models

bp = Blueprint('course', __name__, url_prefix='/course')


@bp.before_app_request
def load_logged_in_user():
    user_id = session.get('user_id')
    if user_id is None:
        g.user = None
    else:
        g.user = Users.get_user(db.session, user_id)


@bp.route('/lesson/<id>')
@login_required
def get_lesson(id):
    course = Courses.get_course(db.session, id)
    if course is None:
        return abort(404)

    s = {}
    attendances = Attendances.get_has_by_user_id(db.session, g.user.id)
    for attendance in attendances:
        s[attendance.timetable_id] = attendance

    alltimetables = course.timetables

    current_id = 0
    course.timetables = []
    for timetable in alltimetables:
        if timetable.state == models.CourseState.signing_in or timetable.state == models.CourseState.started:
            current_id = timetable.id
            break

    for timetable in alltimetables:
        if timetable.id >= current_id:
            course.timetables.append(timetable)

    context = {
        'user': g.user,
        'course': course,
        'randrange': random.randrange,
        'attendances': s,
        'CourseState': models.CourseState,
        'school': current_app.config.get('SCHOOL_NAME')
    }
    return render_template('course/detail.html', **context)
